<template>
  <transition name="viewer-fade">
    <div class="el-image-viewer__wrapper" :style="{ 'z-index': zIndex }">
      <div class="el-image-viewer__mask"></div>
      <!-- Name -->
      <template v-if="imgInfo.name">
        <span class="el-image-viewer__btn el-image-viewer__name">
          {{ imgInfo.name }}
        </span>
      </template>
      <!-- DOWN -->
      <template v-if="imgInfo.id && isHaveFileDownloadAuth">
        <a :href="`/files/download?fileId=${imgInfo.id}`" download="">
          <span
            class="el-image-viewer__btn el-image-viewer__down operation_icon"
          >
            <svg
              t="1626919161000"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="3210"
              xmlns:xlink="http://www.w3.org/1999/xlink"
              width="24"
              height="24"
            >
              <path
                d="M896 672c-17.066667 0-32 14.933333-32 32v128c0 6.4-4.266667 10.666667-10.666667 10.666667H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667v-128c0-17.066667-14.933333-32-32-32s-32 14.933333-32 32v128c0 40.533333 34.133333 74.666667 74.666667 74.666667h682.666666c40.533333 0 74.666667-34.133333 74.666667-74.666667v-128c0-17.066667-14.933333-32-32-32z"
                p-id="3211"
                fill="#e6e6e6"
              ></path>
              <path
                d="M488.533333 727.466667c6.4 6.4 14.933333 8.533333 23.466667 8.533333s17.066667-2.133333 23.466667-8.533333l213.333333-213.333334c12.8-12.8 12.8-32 0-44.8-12.8-12.8-32-12.8-44.8 0l-157.866667 157.866667V170.666667c0-17.066667-14.933333-32-32-32s-34.133333 14.933333-34.133333 32v456.533333L322.133333 469.333333c-12.8-12.8-32-12.8-44.8 0-12.8 12.8-12.8 32 0 44.8l211.2 213.333334z"
                p-id="3212"
              ></path>
            </svg>
          </span>
        </a>
      </template>
      <!-- CLOSE -->
      <span
        style="top: 15px"
        class="el-image-viewer__btn el-image-viewer__close operation_icon"
        @click="hide"
      >
        <svg
          t="1626919430751"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="3460"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          width="24"
          height="24"
        >
          <path
            d="M556.8 512L832 236.8c12.8-12.8 12.8-32 0-44.8-12.8-12.8-32-12.8-44.8 0L512 467.2l-275.2-277.333333c-12.8-12.8-32-12.8-44.8 0-12.8 12.8-12.8 32 0 44.8l275.2 277.333333-277.333333 275.2c-12.8 12.8-12.8 32 0 44.8 6.4 6.4 14.933333 8.533333 23.466666 8.533333s17.066667-2.133333 23.466667-8.533333L512 556.8 787.2 832c6.4 6.4 14.933333 8.533333 23.466667 8.533333s17.066667-2.133333 23.466666-8.533333c12.8-12.8 12.8-32 0-44.8L556.8 512z"
            p-id="3461"
          ></path>
        </svg>
      </span>
      <!-- ARROW -->
      <template v-if="!isSingle">
        <span
          class="el-image-viewer__btn el-image-viewer__prev operation_icon"
          :class="{ 'is-disabled': !infinite && isFirst }"
          @click="prev"
        >
          <i class="el-icon-arrow-left" />
        </span>
        <span
          class="el-image-viewer__btn el-image-viewer__next operation_icon"
          :class="{ 'is-disabled': !infinite && isLast }"
          @click="next"
        >
          <i class="el-icon-arrow-right" />
        </span>
      </template>
      <!-- ACTIONS -->
      <div
        style="bottom: 15px; background: rgba(0, 0, 0, 0.7)"
        class="el-image-viewer__btn el-image-viewer__actions"
      >
        <div class="el-image-viewer__actions__inner">
          <i
            class="el-icon-zoom-out icon"
            @click="handleActions('zoomOut')"
          ></i>
          <i class="el-icon-zoom-in icon" @click="handleActions('zoomIn')"></i>
          <i class="el-image-viewer__actions__divider"></i>
          <i :class="[mode.icon, 'icon']" @click="toggleMode"></i>
          <i class="el-image-viewer__actions__divider"></i>
          <i
            class="el-icon-refresh-left icon"
            @click="handleActions('anticlocelise')"
          ></i>
          <i
            class="el-icon-refresh-right icon"
            @click="handleActions('clocelise')"
          ></i>
        </div>
      </div>
      <!-- CANVAS -->
      <div class="el-image-viewer__canvas">
        <template v-for="(url, i) in urlList">
          <img
            v-if="i === index"
            ref="img"
            class="el-image-viewer__img"
            :key="i"
            :src="currentImg"
            :style="imgStyle"
            @load="handleImgLoad"
            @error="handleImgError"
            @mousedown="handleMouseDown"
          />
        </template>
      </div>
    </div>
  </transition>
</template>

<script>
import { on, off } from "element-ui/src/utils/dom";
import { rafThrottle, isFirefox } from "element-ui/src/utils/util";

const Mode = {
  CONTAIN: {
    name: "contain",
    icon: "el-icon-c-scale-to-original",
  },
  ORIGINAL: {
    name: "original",
    icon: "el-icon-full-screen",
  },
};

const mousewheelEventName = isFirefox() ? "DOMMouseScroll" : "mousewheel";

export default {
  name: "elImageViewer",

  props: {
    urlList: {
      type: Array,
      default: () => [],
    },
    StartIndex: {
      type: Number,
      default: 0,
    },
    zIndex: {
      type: Number,
      default: 2000,
    },
    onSwitch: {
      type: Function,
      default: () => {},
    },
    onClose: {
      type: Function,
      default: () => {},
    },
     info: {
      type: Object,
      default: () => {}
    },
  },

  data() {
    return {
      index: 0,
      isShow: false,
      infinite: true,
      loading: false,
      mode: Mode.CONTAIN,
      transform: {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false,
      },
    };
  },
  computed: {
    /**是否有下载文件的权限 */
    isHaveFileDownloadAuth() {
      return this.info?.fileDownloadAuth ?? true;
    },
    isSingle() {
      return this.urlList.length <= 1;
    },
    isFirst() {
      return this.index === 0;
    },
    isLast() {
      return this.index === this.urlList.length - 1;
    },
    currentImg() {
      const info = this.urlList[this.index] ? this.urlList[this.index] : "";

      return info.url || info;
    },
    imgStyle() {
      const { scale, deg, offsetX, offsetY, enableTransition } = this.transform;
      const style = {
        transform: `scale(${scale}) rotate(${deg}deg)`,
        transition: enableTransition ? "transform .3s" : "",
        "margin-left": `${offsetX}px`,
        "margin-top": `${offsetY}px`,
      };
      if (this.mode === Mode.CONTAIN) {
        style.maxHeight = "510px";
      } else {
        style.maxWidth = style.maxHeight = "100%";
      }
      return style;
    },
    imgInfo() {
      // urls中没有数据
      if (!this.urlList.length) return { url: "", name: "", id: "" };
      const info = this.urlList[this.index];
      if (typeof info === "string") {
        // [url,url,...]格式
        return {
          url: info,
          name: "",
          id: "",
        };
      } else {
        // [{url,name,id},...]格式
        return { ...info, name: info.filename };
      }
    },
  },
  watch: {
    index: {
      handler: function (val) {
        this.reset();
        this.onSwitch(val);
      },
    },
    StartIndex: {
      immediate: true,
      handler: function (val) {
        this.index = val;
      },
    },
    currentImg(val) {
      this.$nextTick((_) => {
        const $img = this.$refs.img[0];
        if (!$img.complete) {
          this.loading = true;
        }
      });
    },
  },
  methods: {
    hide() {
      this.deviceSupportUninstall();
      this.onClose();
    },
    deviceSupportInstall() {
      this._keyDownHandler = rafThrottle((e) => {
        const keyCode = e.keyCode;
        switch (keyCode) {
          // ESC
          case 27:
            this.hide();
            break;
          // SPACE
          case 32:
            this.toggleMode();
            break;
          // LEFT_ARROW
          case 37:
            this.prev();
            break;
          // UP_ARROW
          case 38:
            this.handleActions("zoomIn");
            break;
          // RIGHT_ARROW
          case 39:
            this.next();
            break;
          // DOWN_ARROW
          case 40:
            this.handleActions("zoomOut");
            break;
        }
      });
      this._mouseWheelHandler = rafThrottle((e) => {
        const delta = e.wheelDelta ? e.wheelDelta : -e.detail;
        if (delta > 0) {
          this.handleActions("zoomIn", {
            zoomRate: 0.015,
            enableTransition: false,
          });
        } else {
          this.handleActions("zoomOut", {
            zoomRate: 0.015,
            enableTransition: false,
          });
        }
      });
      on(document, "keydown", this._keyDownHandler);
      on(document, mousewheelEventName, this._mouseWheelHandler);
    },
    deviceSupportUninstall() {
      off(document, "keydown", this._keyDownHandler);
      off(document, mousewheelEventName, this._mouseWheelHandler);
      this._keyDownHandler = null;
      this._mouseWheelHandler = null;
    },
    handleImgLoad(e) {
      this.loading = false;
    },
    handleImgError(e) {
      this.loading = false;
      e.target.alt = this.$t('common.base.loadingFail');
    },
    handleMouseDown(e) {
      if (this.loading || e.button !== 0) return;

      const { offsetX, offsetY } = this.transform;
      const startX = e.pageX;
      const startY = e.pageY;
      this._dragHandler = rafThrottle((ev) => {
        this.transform.offsetX = offsetX + ev.pageX - startX;
        this.transform.offsetY = offsetY + ev.pageY - startY;
      });
      on(document, "mousemove", this._dragHandler);
      on(document, "mouseup", (ev) => {
        off(document, "mousemove", this._dragHandler);
      });

      e.preventDefault();
    },
    reset() {
      this.transform = {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false,
      };
    },
    toggleMode() {
      if (this.loading) return;

      const modeNames = Object.keys(Mode);
      const modeValues = Object.values(Mode);
      const index = modeValues.indexOf(this.mode);
      const nextIndex = (index + 1) % modeNames.length;
      this.mode = Mode[modeNames[nextIndex]];
      this.reset();
    },
    prev() {
      if (this.isFirst && !this.infinite) return;
      const len = this.urlList.length;
      this.index = (this.index - 1 + len) % len;
    },
    next() {
      if (this.isLast && !this.infinite) return;
      const len = this.urlList.length;
      this.index = (this.index + 1) % len;
    },
    handleActions(action, options = {}) {
      if (this.loading) return;
      const { zoomRate, rotateDeg, enableTransition } = {
        zoomRate: 0.2,
        rotateDeg: 90,
        enableTransition: true,
        ...options,
      };
      const { transform } = this;
      switch (action) {
        case "zoomOut":
          if (transform.scale > 0.2) {
            transform.scale = parseFloat(
              (transform.scale - zoomRate).toFixed(3)
            );
          }
          break;
        case "zoomIn":
          transform.scale = parseFloat((transform.scale + zoomRate).toFixed(3));
          break;
        case "clocelise":
          transform.deg += rotateDeg;
          break;
        case "anticlocelise":
          transform.deg -= rotateDeg;
          break;
      }
      transform.enableTransition = enableTransition;
    },
  },
  mounted() {
    this.deviceSupportInstall();
  },
};
</script>
<style scoped>
.el-image-viewer__down {
  top: 15px;
  right: 114px;
  font-size: 40px;
  position: fixed;
  opacity: 0.6;
}
.el-image-viewer__name {
  position: fixed;
  color: #ffffff;
  left: 0;
  right: 0;
  margin: auto;
  top: 25px;
  text-shadow: 0.1em 0.1em 0.05em #333;
}
.icon {
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.5s;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon:hover {
  background: rgba(0, 0, 0, 0.5);
}
.operation_icon {
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  width: 44px;
  height: 44px;
  transition: all 0.5s;
}
.operation_icon:hover {
  background: rgba(0, 0, 0, 1);
}
.operation_icon svg {
  fill: #9a9a9a;
  transition: all 0.5s;
}
.operation_icon:hover svg {
  fill: #ffffff;
}
.operation_icon > i {
  color: rgb(154, 154, 154);
  transition: all 0.5s;
}
.operation_icon:hover > i {
  color: #ffffff;
}
</style>